/**
 * Created by yesi on 15/5/16.
 */
var fs = require("fs");
var common = require("./common/common");
var querystring = require("querystring");
var mongo = require("./mongo/mongo");
var usernameKey = "username";


function toLogin(postData,response) {
    response.statusCode = 302;
    response.setHeader("Location", "/login.html");
    response.end();
}

function toRegist(postData,response) {
    response.statusCode = 302;
    response.setHeader("Location", "/regist.html");
    response.end();
}

function doLogin(postData,response) {
    var params = querystring.parse(postData);
    console.log(params);
    mongo.connect(function(err,db){
       mongo.findByDb(params,mongo.user,db,function(err,data,db){
           if(err){return proccessMongoError(err,response,db);}
           if(data==null || data.length==0){
               db.close();
               return common.write200(response,common.createFailData("用户名或密码错误"));
           }
           if(params.password!=data[0].password){
               db.close();
               return common.write200(response,common.createFailData("用户名或密码错误"));
           }
           var queryObj = new Object();
           queryObj.cookie = process.domain.cookie;
           mongo.findByDb(queryObj,mongo.cookie,db,function(err,cookieData,db){
               if(err){return proccessMongoError(err,response,db);}
               var updateObj = new Object();
               updateObj.cookie = process.domain.cookie;
               updateObj.username = data[0].username;
               if(cookieData==null || cookieData.length==0){
                   mongo.insertByDb(updateObj,mongo.cookie,db,function(err,result,db){
                       if(err){return proccessMongoError(err,response,db);}
                       common.write200(response,common.createSuccessData(data[0]));
                       db.close();
                   });
               }else{
                   mongo.updateByDb(queryObj,updateObj,mongo.cookie,db,function(err,result,db){
                       if(err){return proccessMongoError(err,response,db);}
                       common.write200(response,common.createSuccessData(data[0]));
                       db.close();
                   });
               }
           });
       });
    });

}

function doRegist(postData,response) {
    var params = querystring.parse(postData);
    console.log(params);
    mongo.connect(function(err,db){
        if(err){return proccessMongoError(err,response,db);}
        var query = new Object();
        query.username = params[usernameKey];
        mongo.findByDb(query,mongo.user,db,function(err,result,db){
            if(err){return proccessMongoError(err,response,db);}
            if(result!=null && result.length>0){
                common.write200(response,common.createFailData("用户名已被注册"));
                db.close();
                return;
            }
            mongo.insertByDb(params,mongo.user,db,function(err,result,db){
                if(err){return proccessMongoError(err,response,db);}
                common.write200(response,common.createSuccessData(result));
                db.close();
            });
        });
    });

}

function doShowData(postData,response){
    var cookie = process.domain.cookie;
    if(cookie==null){return common.write200(response,common.createFailData("请先登录!"));}
    //差cookie对应的id
    mongo.connect(function(err,db){
        var query = new Object();
        query.cookie = cookie;
        mongo.findByDb(query,mongo.cookie,db,function(err,result,db){
            if(err){return proccessMongoError(err,response,db);}
            if(result==null || result.length==0){
                db.close();
                return common.write200(response,common.createFailData("请先登录!"));
            }
            var userQuery = new Object();
            userQuery.username = result[0].username;
            mongo.findByDb(userQuery,mongo.user,db,function(err,result,db){
                if(err){return proccessMongoError(err,response,db);}
                if(result==null || result.length==0){
                    db.close();
                    return common.write200(response,common.createFailData("请先注册!"));
                }
                common.write200(response,common.createSuccessData(result[0]));
                db.close();
            });
        });
    });
}

function proccessMongoError(err,response,db){
    console.log(err);
    if(typeof(db) != "undefined"){db.close();}
    common.write200(response,common.createFailData("mongo报错，请检查配置, 错误信息:"+err));
    return;
}

function static(pathname,response){
    var realPath = "views" + pathname;
    var ext = pathname.match(/(\.[^.]+|)$/)[0];
    console.log("request static "+pathname+" sufix="+ext);
    var contentType = "";
    if(ext==".css"){
        contentType = "text/css";
    }else if(ext==".js"){
        contentType = "application/javascript";
    }else{
        contentType = "text/html";
    }
    fs.readFile(realPath, 'utf-8', function (err, data) {//读取内容
        if (err) {
            common.write404(response);
            return;
        }
        common.setHeader(response,"Content-Type",contentType);
        common.write200(response,data);
    });
}

exports.toLogin = toLogin;
exports.toRegist = toRegist;
exports.doLogin = doLogin;
exports.doRegist = doRegist;
exports.doShowData = doShowData;
exports.static = static;